package cn.congine.wizarpos.mall.action;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.Merchandise;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncInput;
import cn.congine.wizarpos.mall.model.open.MerchandiseSyncOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryInput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryOutput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberInfoQueryOutput.Result;
import cn.congine.wizarpos.mall.service.impl.WPosHttpClient;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.Function;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.WxSignUtil;

@Controller
@RequestMapping(value = "/merchant")
public class SysMerchantDefAction {

	@Autowired
	private WPosHttpClient wposHttpClient;

	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;	
	
	@Resource(name = "messageSource")
	private MessageSource messageSource;

	private static Logger log = LoggerFactory
			.getLogger(SysMerchantDefAction.class);
	
	/**
	 * 商户信息
	 * 
	 * @param mid
	 * @param openId
	 * @return
	 * @throws Exception 
	 */

	@RequestMapping(value = "/info")
	public ModelAndView getSysMerchantDef(
			@RequestParam(value = "mid") String mid,
			@RequestParam(value = "openId") String openId,
			HttpServletRequest httpRequest) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> getpricehot = new HashMap<String, Object>();
		Map<String, Object> getmberpricehot = new HashMap<String, Object>();
		
		MerchantDefQueryInput merchantDefQueryInput = new MerchantDefQueryInput();
		merchantDefQueryInput.setMid(mid);
		MerchantDefQueryOutput MerchantDefouptut = (MerchantDefQueryOutput) wizarposOpenRestClient.post(merchantDefQueryInput, "/merchantdef/info", MerchantDefQueryOutput.class);
		MerchantDef merchant = MerchantDefouptut.getResult();
		if (merchant == null) {
			data.put("err_message", "该商户不存在");
			return new ModelAndView("error", data);
		}
		
		WeChartMemberInfoQueryInput weChartMemberInfoQueryinput = new WeChartMemberInfoQueryInput();
		weChartMemberInfoQueryinput.setMid(mid);
		weChartMemberInfoQueryinput.setOpenId(openId);
		WeChartMemberInfoQueryOutput weChartMemberInfoQueryOutput = (WeChartMemberInfoQueryOutput) wizarposOpenRestClient.post(weChartMemberInfoQueryinput, "/wechart/info/query", WeChartMemberInfoQueryOutput.class);
		
		MerchandiseSyncInput merchandiseSyncInput = new MerchandiseSyncInput();		
		merchandiseSyncInput.setMid(mid);
		MerchandiseSyncOutput merchandiseSyncOutput = (MerchandiseSyncOutput) wizarposOpenRestClient.post(merchandiseSyncInput, "/product/merchandise", MerchandiseSyncOutput.class);		

		// 判断是否存在mid和openId
		Result card = weChartMemberInfoQueryOutput.getResult();
		boolean cardIsExist = false;
		if (card != null) {
			cardIsExist = true;
		}

		List<Merchandise> producthot = merchandiseSyncOutput.getResult();
		for (Merchandise erpProduct : producthot) {
			getpricehot.put(erpProduct.getProductId(), erpProduct.getPrice());  
			getmberpricehot.put(erpProduct.getProductId(), erpProduct.getMemberPrice());
			// 商品图片---多张
			if ("".equals(erpProduct.getPicUrl())) {
				erpProduct.setPicUrl(SysConstants.DEFAULT_PICTURE);
			} else {
				erpProduct.setPicUrl(Function.dealGridPicUrl(erpProduct.getPicUrl(), 150, 150));
			}
		}
		data.put("producthot", producthot);
		data.put("getmberpricehot", getmberpricehot);
		data.put("merchant", merchant);
		data.put("cardIsExist", cardIsExist);
		data.put("openId", openId);
		data.put("mid", mid);
		
		//请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS , null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext().getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/merchant/info");
		tmpUrl.append("?mid=").append(mid);
		tmpUrl.append("&openId=").append(openId);
		String url = tmpUrl.toString();
		//请求微信api的ticket
		//程序部署公众号的商户号
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		
		return new ModelAndView("merchant/merchant_info", data);
	}
}
